﻿using System.Collections.Generic;
using System.Linq.Expressions;

namespace IDI.Studio.Core
{
    public class ParameterReplacer : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> parameters;

        public ParameterReplacer(Dictionary<ParameterExpression, ParameterExpression> parameters)
        {
            this.parameters = parameters ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> parameters, Expression node)
        {
            return new ParameterReplacer(parameters).Visit(node);
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            ParameterExpression parameterExpression;

            if (parameters.TryGetValue(node, out parameterExpression))
            {
                node = parameterExpression;
            }

            return base.VisitParameter(node);
        }
    }
}
